﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace SinaWeiboPlugin
{
    class MultiPartBuilder:IDisposable
    {
        private MemoryStream _memStream = new MemoryStream();

        private String _boundary = "--------------------" + DateTime.Now.Ticks.ToString("x");
        public String Boundary
        {
            get { return _boundary; }
        }

        private byte[] _boundBytes
        {
            get
            {
                return System.Text.Encoding.ASCII.GetBytes("\r\n--" +  _boundary + "\r\n");
            }
        }

        private String _formateKV = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
        private String _formateFile = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";

        public byte[] Result
        {
            get { return _memStream.ToArray(); }
        }

        public MultiPartBuilder()
        {
        }

        public void Append(String key,String value)
        {
            _memStream.Write(_boundBytes, 0, _boundBytes.Length);
            string formitem = string.Format(_formateKV, key, value);
            byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
            _memStream.Write(formitembytes, 0, formitembytes.Length);
        }

        public void Append(String key, byte[] file, String filePath, String fileType)
        {
            _memStream.Write(_boundBytes, 0, _boundBytes.Length);
            string header = String.Format(_formateFile, key, filePath, fileType);
            byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
            _memStream.Write(headerbytes, 0, headerbytes.Length);

            _memStream.Write(file, 0, file.Length);
        }

        public void End()
        {
           byte[] endBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" +  _boundary + "--\r\n");
           _memStream.Write(endBytes, 0, endBytes.Length);
        }

        #region IDisposable Members

        public void Dispose()
        {
            _memStream.Close();
            _memStream = null;
        }

        #endregion
    }
}
